package utilx

import (
	"crypto/md5"
	"encoding/hex"

	"golang.org/x/crypto/bcrypt"
)

// HashAndSaltPassword 密码加密
func HashAndSaltPassword(pwd []byte) (string, error) {
	if hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost); err != nil {
		return "", err
	} else {
		return string(hash), nil
	}
}

// ComparePasswords 验证密码
func ComparePasswords(hashedPwd string, plainPwd []byte) bool {
	byteHash := []byte(hashedPwd)
	if err := bcrypt.CompareHashAndPassword(byteHash, plainPwd); err != nil {
		return false
	}
	return true
}

// Md5 md5加密
func Md5(src string) string {
	m := md5.New()
	m.Write([]byte(src))
	return hex.EncodeToString(m.Sum(nil))
}
